package com.hzjh.base.ext.widget.recycleview

import android.content.Context
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hzjh.base.ext.R
import com.hzjh.base.ext.databinding.JhImageUpItemBinding
import com.hzjh.base.ext.widget.dialog.SelectGetPictureModeDialog
import com.hzjh.base.frame.activity.AbsActivity
import com.hzjh.base.frame.adapter.MutableAdapter
import com.hzjh.base.frame.adapter.SimpleGapItemDecor
import com.hzjh.base.log.JHLogger
import com.hzjh.base.style.weight.ToastKt.toastCenter
import com.hzjh.base.utils.function.dp2px
import com.hzjh.base.utils.other.CheckUtils
import com.hzjh.base.utils.other.CommUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DateUtils
import com.luck.picture.lib.utils.MediaUtils
import com.luck.picture.lib.utils.PictureFileUtils
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File

class JHImageUpView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    styleTheme: Int = 0
) : RecyclerView(context, attrs, styleTheme) {
    private val dataList: MutableList<String> = mutableListOf()
    private var activity: AbsActivity? = null
    private var jhImageUpViewI: ((String) -> Unit)? = null
    private var enabled: Boolean = true
    private val dataAdapter by lazy {
        MutableAdapter(dataList).apply {
            addVhDelegate {
                JHImageUpItemVH(JhImageUpItemBinding.inflate(LayoutInflater.from(context),it,false),
                    delete = {position->
                        //图片删除
                        if(!enabled){
                            context.toastCenter(CommUtils.getString(R.string.jh_image_tip1))
                            return@JHImageUpItemVH
                        }
                        dataList.removeAt(position)
                        if(dataList.size==0){
                            dataList.add("")
                        }
                        notifyDataSetChanged()
                    },
                    add={
                        //图片添加上传
                        if(!enabled){
                            context.toastCenter(CommUtils.getString(R.string.jh_image_tip2))
                            return@JHImageUpItemVH
                        }
                        activity?.let {activity->
                            SelectGetPictureModeDialog()
                                .show(activity.supportFragmentManager, SelectGetPictureModeDialog::class.simpleName)

                            activity.supportFragmentManager.setFragmentResultListener(
                                SelectGetPictureModeDialog.REQUEST_KEY_GET_PICTURE_MODE,
                                activity
                            ) { _, bundle ->
                                val getPictureMode = bundle.getInt(SelectGetPictureModeDialog.BUNDLE_KEY_GET_PICTURE_MODE)
                                JHLogger.d("getPictureMode=$getPictureMode")
                                if (getPictureMode == SelectGetPictureModeDialog.GET_PICTURE_MODE_TAKE_PICTURE) {
                                    getPictureByTakePhoto()
                                } else {
                                    getPictureBySystemGallery()
                                }
                            }
                        }
                    }, enable ={
                        enabled
                    })
            }
        }
    }
    init {
        activity = context as? AbsActivity
        layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        addItemDecoration(
            SimpleGapItemDecor(horGap = 14.dp2px())
        )
        adapter=dataAdapter
        dataList.add("")
        dataAdapter.notifyDataSetChanged()
    }

    //设置图片
    fun setData(data: List<String>?) {
        dataList.clear()
        data?.let {
            dataList.addAll(it)
        }
        if(dataList.size<3){
            dataList.add("")
        }
        dataAdapter.notifyDataSetChanged()
    }
    //添加图片
    fun addImageUrl(imgUrl:String){
        JHLogger.d("图片地址=$imgUrl")
        dataList.add(dataList.size-1,imgUrl)
        if(dataList.size>3){
            dataList.removeLast()
        }
        dataAdapter.notifyDataSetChanged()
    }

    //获取图片列表
    fun getData():List<String>{
        return dataList.filter { !CheckUtils.isEmpty(it) }
    }

    //图片禁止上传
    fun disableUpload(){
        enabled=false
    }

    // 使用系统相机拍照
    private fun getPictureByTakePhoto() {
        PictureSelector.create(activity)
            .openCamera(SelectMimeType.ofImage())
            .setCompressEngine(ImageFileCompressEngine()) //压缩图片
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    analyticalSelectResults(result)
                    if (result.isNotEmpty()) {
                        JHLogger.d("TakePhoto=${result[0].availablePath}")
                        handleSelectedPicture(result[0].availablePath)
                    }
                }

                override fun onCancel() {
                    JHLogger.d( "PictureSelector Cancel")
                }
            })
    }

    // 从系统相册选择
    private fun getPictureBySystemGallery() {
        PictureSelector.create(activity)
            .openSystemGallery(SelectMimeType.ofImage()) //从系统相册选图
            .setSelectionMode(SelectModeConfig.SINGLE) //单选
            .setCompressEngine(ImageFileCompressEngine()) //压缩图片
            .setSkipCropMimeType(PictureMimeType.ofGIF(), PictureMimeType.ofWEBP()) //跳过不需要裁剪的类型
//                .setCustomLoadingListener(getCustomLoadingListener())
            .forSystemResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    analyticalSelectResults(result)
                    if (!result.isEmpty()) {
                        handleSelectedPicture(result[0].availablePath)
                    }
                }

                override fun onCancel() {
                    JHLogger.d("PictureSelector Cancel")
                }
            })
    }

    /**
     * 处理已选择的图片
     */
    fun handleSelectedPicture(image: String) {
        JHLogger.d("onImageSelect=$image")
        jhImageUpViewI?.invoke(image)
    }

    /**
     * 自定义压缩
     */
    private class ImageFileCompressEngine : CompressFileEngine {
        override fun onStartCompress(
            context: Context,
            source: java.util.ArrayList<Uri>,
            call: OnKeyValueResultCallbackListener
        ) {
            Luban.with(context).load(source)
                .setRenameListener { filePath ->
                    // 设置压缩后的文件名
                    val indexOf = filePath.lastIndexOf(".")
                    val postfix = if (indexOf != -1) filePath.substring(indexOf) else ".jpg"
                    DateUtils.getCreateFileName("CMP_") + postfix
                }.filter { path ->
                    // 仅压缩图片，Gif跳过
                    if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) {
                        true
                    } else {
                        !PictureMimeType.isUrlHasGif(path)
                    }
                }.setCompressListener(object : OnNewCompressListener {
                    override fun onStart() {}
                    override fun onSuccess(source: String, compressFile: File) {
                        if (call != null) {
                            call.onCallback(source, compressFile.absolutePath)
                        }
                    }

                    override fun onError(source: String, e: Throwable?) {
                        if (call != null) {
                            call.onCallback(source, null)
                        }
                    }
                }).launch()
        }
    }

    /**
     * 处理选择结果
     *
     * @param result
     */
    private fun analyticalSelectResults(result: ArrayList<LocalMedia>) {
        if (result == null) return
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo = MediaUtils.getImageSize(context, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo = MediaUtils.getVideoSize(context, media.path)
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
            JHLogger.d("文件名: " + media.fileName)
            JHLogger.d("是否压缩:" + media.isCompressed)
            JHLogger.d("压缩:" + media.compressPath)
            JHLogger.d("初始路径:" + media.path)
            JHLogger.d("绝对路径:" + media.realPath)
            JHLogger.d("是否裁剪:" + media.isCut)
            JHLogger.d("裁剪路径:" + media.cutPath)
            JHLogger.d("是否开启原图:" + media.isOriginal)
            JHLogger.d("原图路径:" + media.originalPath)
            JHLogger.d("沙盒路径:" + media.sandboxPath)
            JHLogger.d("水印路径:" + media.watermarkPath)
            JHLogger.d("视频缩略图:" + media.videoThumbnailPath)
            JHLogger.d("原始宽高: " + media.width + "x" + media.height)
            JHLogger.d("裁剪宽高: " + media.cropImageWidth + "x" + media.cropImageHeight)
            JHLogger.d(
                "文件大小: " + PictureFileUtils.formatAccurateUnitFileSize(media.size)
            )
            JHLogger.d("文件时长: " + media.duration)
        }
    }

    fun setJHImageUpViewI(jhImageUpViewI: (String) -> Unit){
        this.jhImageUpViewI = jhImageUpViewI
    }
}